package com.richapp.launcher.service;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.jack.netty.log.LoggerManager;
import com.jack.netty.tcp.client.TLVClient;
import com.jack.netty.tcp.client.TLVClientListener;
import com.richapp.launcher.IMyAidlInterface;
import com.richapp.launcher.busevent.EventServiceDestroy;
import com.richapp.launcher.net.remote.RemoteClient;
import com.richapp.launcher.utils.DeanTLVClient;
import com.richapp.launcher.utils.Tools;
import com.tencent.bugly.beta.Beta;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import de.greenrobot.event.EventBus;

/**
 * Created by wujinguang on 2017/4/24.
 */
public class LocalService extends Service {
    public MyBinder binder;
    public MyConn conn;
    public int CYCLIC_TIME=5;
//    boolean flag= Tools.ping();

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    boolean isRun = false;
                    // 获取activity管理对象
                    ActivityManager activityManager = (ActivityManager) getApplicationContext()
                            .getSystemService(Context.ACTIVITY_SERVICE);
                            //  获取所有正在运行的app
                    List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
                    if(appProcesses.size()!=0){
                //     遍历app，获取应用名称或者包名
                    for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                        if (appProcess.processName.equals("com.richapp.launcher")) {
                            isRun = true;
//                            Log.i("app", appName + "在运行");
                            break;
                        }
                    }
                    }
                    ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
                    String currentPackageName = cn.getPackageName();
                    if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getApplicationContext().getPackageName())) {
                        isRun = true;
                    }
                    if(!isRun){
                        Log.i("LocalService", "我动了" + isRun);
//                        //启动应用
//                         Context context= getApplicationContext();
//                        Intent app = context.getPackageManager().getLaunchIntentForPackage("com.richapp.launcher");
//                        context.startActivity(app);
                    }
                    Log.i("LocalService", "我动了" + isRun);
//                    delayedStopRemoteClient();
//                    startClient();//检测主机是否连接服务端
                    //检查更新2/5分钟检测一次
                    Beta.checkUpgrade();
                    handler.sendEmptyMessageDelayed(1, 1000 * 60 * CYCLIC_TIME);
                    break;
            }
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        binder = new MyBinder();
        conn = new MyConn();

        handler.sendEmptyMessageDelayed(1, 1000 * 10);
    }

    class MyBinder extends IMyAidlInterface.Stub {
        @Override
        public String getServiceName() throws RemoteException {
            return LocalService.class.getSimpleName();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.v(LocalService.class.getSimpleName(),"本地服务启动");
        try {
            this.bindService(new Intent(LocalService.this, RomoteService.class), conn, Context.BIND_IMPORTANT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            //开启远程服务
            LocalService.this.startService(new Intent(LocalService.this, RomoteService.class));
            //绑定远程服务
            LocalService.this.bindService(new Intent(LocalService.this, RomoteService.class), conn, Context.BIND_IMPORTANT);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //开启远程服务
        LocalService.this.startService(new Intent(LocalService.this, RomoteService.class));
        //绑定远程服务
        LocalService.this.bindService(new Intent(LocalService.this, RomoteService.class), conn, Context.BIND_IMPORTANT);

    }



    public void  delayedStopRemoteClient(){
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                /**
                 *要执行的操作
                 */
                if (!Tools.ping()){
                    CYCLIC_TIME=2;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RemoteClient.getInstance().stop();
                                LoggerManager.getInstance().getiLogger().warn(getClass(), "外网服务器连接服务销毁!");
                                EventBus.getDefault().post(new EventServiceDestroy(RemoteService.class));
                            }
                        }).start();

                }else {
                    CYCLIC_TIME=5;
                    if(RemoteClient.getInstance().isConnected()==false){
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                RemoteClient.getInstance().start();
                            }
                        }).start();
                        //保持服务
                        Notification notification = new Notification();
                        startForeground(5, notification);
                        LoggerManager.getInstance().getiLogger().info(getClass(),"外网服务器连接服务启动!");
                        EventBus.getDefault().post(new EventServiceDestroy(RemoteService.class));
                    }
                }


            }
        };
        Timer timer = new Timer();
        timer.schedule(task, 1000);//10秒后执行TimeTask的run方法


    }


    public static void startClient(){
        if (Tools.ping()) {
            if (!RemoteClient.getInstance().isConnected()) {
                final DeanTLVClient client = new DeanTLVClient();
                client.setIp("39.108.55.223");//岂控
//                client.setIp("120.26.199.77");//赛天
                client.setPort(53654);
                client.setTlvClientListener(new TLVClientListener() {
                    public void onConnect(String serverId) {
                        client.sendMessage("");
                    }

                    public void onDisconnect(String serverId) {
                    }

                    public void onMessage(String serverId, String message) {
                        client.sendMessage("");
                    }
                });

                (new Thread(new Runnable() {
                    public void run() {
                        client.start();
                    }
                })).start();

            }
        }
    }

}